package cn.aitstone.pet.service.impl;

import cn.aitstone.basic.exception.BusinessException;
import cn.aitstone.basic.utils.*;
import cn.aitstone.order.domain.OrderPetAcquisition;
import cn.aitstone.order.mapper.OrderPetAcquisitionMapper;
import cn.aitstone.org.domain.Employee;
import cn.aitstone.org.domain.Shop;
import cn.aitstone.org.mapper.EmployeeMapper;
import cn.aitstone.org.mapper.ShopMapper;
import cn.aitstone.pet.domain.Pet;
import cn.aitstone.pet.domain.SearchMasterMsg;
import cn.aitstone.pet.domain.SearchMasterMsgAuditLog;
import cn.aitstone.pet.dto.HandleMsgDto;
import cn.aitstone.pet.mapper.PetMapper;
import cn.aitstone.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.aitstone.pet.mapper.SearchMasterMsgMapper;
import cn.aitstone.pet.service.ISearchMasterMsgService;
import cn.aitstone.basic.service.impl.BaseServiceImpl;
import cn.aitstone.user.domain.User;
import cn.aitstone.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Sheldon
 * @since 2022-07-19
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RocketMQProducer rocketMQProducer;

    @Override
    public void publish(SearchMasterMsg searchMasterMsg, User user) {
        // 第一步保存寻主消息到库中
        searchMasterMsgMapper.save(searchMasterMsg);
        StringBuffer sbf = new StringBuffer()
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getName())
                .append(searchMasterMsg.getCoatColor())
                .append(searchMasterMsg.getTitle());
        /* 审核用户填写的信息是否有违规的地方 */
        if (!BaiduAuditUtils.TextCensor(sbf.toString())){
            // 设置审核状态为驳回
            searchMasterMsg.setState(-1);
            // 创建寻主消息日志记录对象
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            // 设置寻主消息日志记录的msgId
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            // 设置寻主消息日志记录的状态为0，这表示审核失败
            searchMasterMsgAuditLog.setState(0);
            // 设置备注
            searchMasterMsgAuditLog.setNote("输入的信息不合法，可能是：名称、地址、描述、毛色等");
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
        } else {
            // 设置审核状态为通过
            searchMasterMsg.setState(1);
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            // 获取库中所有店铺
            List<Shop> shops = shopMapper.loadAll();
            // 调用工具类方法得到距离最近的店铺
            Shop shop = DistanceUtil.getNearestShop(point, shops);
            if (shop != null){
                searchMasterMsg.setShopId(shop.getId());
            }

        }
        searchMasterMsgMapper.update(searchMasterMsg);

    }

    /**
    * @Title: accept
    * @Description: 接单
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/20 18:26
    * @Parameters: [handleMsgDto]
    * @Return void
    */
    @Override
    public void accept(HandleMsgDto handleMsgDto) {
        /* 参数校验 */
        if (StringUtils.isEmpty(handleMsgDto.getHandler()) || StringUtils.isEmpty(handleMsgDto.getNote())){
            throw new BusinessException("参数不能为空");
        }
        // 查询此订单是否已经被接了，以及是否是取消的订单
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadByMsgIdAndNotCanceled(handleMsgDto.getMsgId());

        if (orderPetAcquisition != null){
            throw new BusinessException("此寻主消息已经被接单了");
        }
        // 根据寻主消息的主键id找到寻主消息对象
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(handleMsgDto.getMsgId());
        Pet pet = msg2Pet(searchMasterMsg);
        petMapper.save(pet);


        orderPetAcquisition = initOrderPetAcquisition(handleMsgDto, searchMasterMsg, pet);

        orderPetAcquisitionMapper.save(orderPetAcquisition);

        rocketMQProducer.sendDelayMsg(orderPetAcquisition.getId().toString(), 6);



    }

    @Override
    public void reject(Long msgId) {
        // 参数校验
        if (msgId == null){
            throw new BusinessException("参数不能为空");
        }
        // 根据消息Id查询寻主消息，将shopId置空，并修改
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        if (searchMasterMsg == null){
            throw new BusinessException("此订单不存在！");
        }
        searchMasterMsg.setShopId(null);
        searchMasterMsgMapper.update(searchMasterMsg);
        // 记录日志，自行完成，自己判断那张表是拒单日志表，如果没有自己创建
    }

    /**
    * @Title: extracted
    * @Description: 初始化订单对象
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/20 18:23  
    * @Parameters: [handleMsgDto, orderPetAcquisition, searchMasterMsg, pet]
    * @Return void
    */
    private OrderPetAcquisition initOrderPetAcquisition(HandleMsgDto handleMsgDto, SearchMasterMsg searchMasterMsg, Pet pet) {
        OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(searchMasterMsg.getUserId());
        System.out.println(orderSn);
        orderPetAcquisition.setOrderSn(orderSn);
        orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setDigest(handleMsgDto.getNote() + "接单了-"+ pet.getName());
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        orderPetAcquisition.setShopId(searchMasterMsg.getShopId());
        orderPetAcquisition.setEmpId(handleMsgDto.getHandler());
        orderPetAcquisition.setPrice(searchMasterMsg.getPrice());
        orderPetAcquisition.setPetId(pet.getId());
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        return orderPetAcquisition;
    }

    /**
    * @Title: msg2Pet
    * @Description: 初始化宠物基本信息对象
    * @Author: Sheldon
    * @Version: 1.0
    * @Date:  2022/7/20 18:04  
    * @Parameters: [searchMasterMsg]
    * @Return cn.aitstone.pet.domain.Pet
    */
    private Pet msg2Pet(SearchMasterMsg searchMasterMsg){
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setTypeId(searchMasterMsg.getPetType());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        return pet;
    }
}
